// 仪表盘功能实现

DOM.on(window, 'load', () => {
  // 渲染最近订单表格
  function renderRecentOrders() {
    const ordersTable = DOM.$('#recent-orders-table tbody');
    ordersTable.innerHTML = '';
    
    // 获取最近的10个订单
    const ordersData = dataManager.getOrders({}, 1, 10);
    
    ordersData.orders.forEach(order => {
      const row = DOM.create('tr');
      
      // 格式化日期
      const date = new Date(order.createdAt).toLocaleString('zh-CN');
      
      // 获取状态标签
      const statusLabel = orderStatusMachine.getStateLabel(order.status);
      
      // 根据状态设置徽章样式
      let badgeClass = '';
      switch (order.status) {
        case 'PENDING': badgeClass = 'badge-warning'; break;
        case 'PAID': badgeClass = 'badge-primary'; break;
        case 'SHIPPED': badgeClass = 'badge-info'; break;
        case 'DELIVERED': badgeClass = 'badge-success'; break;
        case 'COMPLETED': badgeClass = 'badge-success'; break;
        case 'CANCELLED': badgeClass = 'badge-secondary'; break;
        case 'REFUNDED': badgeClass = 'badge-danger'; break;
        case 'RETURNED': badgeClass = 'badge-danger'; break;
        default: badgeClass = 'badge-secondary';
      }
      
      // 构建订单商品信息显示
      let productInfo = '';
      if (order.products.length > 1) {
        productInfo = `${order.products[0].productName} 等${order.products.length}件商品`;
      } else {
        const product = order.products[0];
        const variantInfo = product.variant.attributes 
          ? Object.values(product.variant.attributes).join(' / ') 
          : '';
        productInfo = `${product.productName} ${variantInfo}`;
      }
      
      row.innerHTML = `
        <td>${order.id}</td>
        <td>${order.customer.name}</td>
        <td>¥${order.totalAmount.toFixed(2)}</td>
        <td><span class="badge ${badgeClass}">${statusLabel}</span></td>
        <td>${date}</td>
        <td>
          <button class="btn btn-secondary" style="padding: 4px 12px; font-size: 12px;" data-order-id="${order.id}">
            查看详情
          </button>
        </td>
      `;
      
      ordersTable.appendChild(row);
    });
    
    // 绑定查看详情按钮事件
    DOM.$$('#recent-orders-table [data-order-id]').forEach(btn => {
      DOM.on(btn, 'click', () => {
        const orderId = btn.getAttribute('data-order-id');
        // 切换到订单页面
        viewManager.switchTo('orders');
        // 这里可以添加定位到特定订单的逻辑
        setTimeout(() => {
          const orderEl = DOM.$(`[data-order-id="${orderId}"]`);
          if (orderEl) {
            orderEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
          }
        }, 100);
      });
    });
  }
  
  // 更新统计数据
  function updateStats() {
    // 计算今日销售额
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const todayOrders = dataManager.data.orders.filter(order => {
      const orderDate = new Date(order.createdAt);
      return orderDate >= today && 
             (order.status === 'PAID' || order.status === 'SHIPPED' || 
              order.status === 'DELIVERED' || order.status === 'COMPLETED');
    });
    
    const todaySales = todayOrders.reduce((sum, order) => sum + order.totalAmount, 0);
    
    // 计算待处理订单数
    const pendingOrders = dataManager.data.orders.filter(order => 
      order.status === 'PENDING' || order.status === 'PAID' || order.status === 'SHIPPED'
    ).length;
    
    // 更新统计卡片
    const statsCards = DOM.$$('.stats-card');
    if (statsCards.length > 0) {
      // 今日销售额
      statsCards[0].querySelector('.value').textContent = `¥${todaySales.toFixed(0)}`;
    }
    if (statsCards.length > 1) {
      // 今日订单
      statsCards[1].querySelector('.value').textContent = todayOrders.length.toString();
    }
    if (statsCards.length > 3) {
      // 待处理订单
      statsCards[3].querySelector('.value').textContent = pendingOrders.toString();
    }
  }
  
  // 初始化仪表盘
  function initDashboard() {
    renderRecentOrders();
    updateStats();
    
    // 监听视图切换事件，当切换到仪表盘时重新渲染
    DOM.on(document, 'viewChanged', (e) => {
      if (e.detail.viewId === 'dashboard') {
        renderRecentOrders();
        updateStats();
      }
    });
    
    // 每30秒自动刷新一次数据
    setInterval(() => {
      if (viewManager.currentView === 'dashboard') {
        updateStats();
      }
    }, 30000);
  }
  
  // 初始化
  initDashboard();
});